import React, { useState, useEffect } from 'react'
import { Card, List, Button, message } from 'antd'
import { ArrowLeftOutlined } from '@ant-design/icons'
import { withRouter, useHistory } from 'react-router-dom'
import { useSelector, shallowEqual,useDispatch } from 'react-redux'
import ajax from '../../service/ajax'
import { BASE_URL } from '../../config/constants'
import './detail.less'
import {saveCategoryListAction} from '../../store/actionCreators/admin'

const { Item } = List

function Detail(props) {
  const [DetailList, setDetaiList] = useState({})
  const id = props.match.params.id
  const history = useHistory()
  const dispatch = useDispatch()
  const { adminInfo } = useSelector((state) => ({
    adminInfo: state.adminInfo.categoryList
  }), shallowEqual)

  useEffect(() => {
    getDetail(id)
  }, [])
  const getDetail = async (id) => {
    if(adminInfo.length === 0){
      dispatch(saveCategoryListAction())
    }
    let result = await ajax('/manage/product/info', { params: { productId: id } })
    const { status, data } = result
    if (status === 0) {
      setDetaiList(result.data)
    } else {
      message.error('商品详情请求失败')
    }
  }

  const getCategoryName = (id) => {
    return adminInfo.find((item) => {
      if(item._id === id) {
        return item.name
      }
    })
  }

  return (
    <Card title={
      <div>
        <Button
          type="link"
          onClick={() => history.go(-1)}
        >
          <ArrowLeftOutlined />
          返回
        </Button>
        <span>商品详情</span>
      </div>
    }>
      <List>
        <Item className="detail-title">
          <span>商品名称：</span>
          <span>{DetailList.name}</span>
        </Item>
        <Item className="detail-title">
          <span>商品描述：</span>
          <span>{DetailList.desc}</span>
        </Item>
        <Item className="detail-title">
          <span>商品价格：</span>
          <span>{DetailList.price}</span>
        </Item>
        <Item className="detail-title">
          <span>商品分类：</span>
          <span>{getCategoryName(id)}</span>
        </Item>
        <Item className="detail-title">
          <span>商品图片：</span>
          {DetailList.imgs && DetailList.imgs.map((item, index) => {
            return <img key={index} src={`${BASE_URL}/upload/${item}`} alt="商品图片" style={{ width: '200px' }} />
          })}
        </Item>
        <Item className="detail-title">
          <span className="detail-title">商品详情：</span>
          <span className="detail-list" dangerouslySetInnerHTML={{ __html: DetailList && DetailList.detail }}></span>
        </Item>
      </List>
    </Card>
  )
}

export default withRouter(Detail)